var t, a = getApp();

Page({
    data: {
        items: [],
        startX: 0,
        startY: 0,
        toView: "blue",
        zujiIcon: "../../res/images/icon-zuji.png",
        zijiName: "推荐商品",
        selectedMenuId: 1,
        is_first_action: !0,
        total: {
            count: 0,
            money: 0
        },
        cartMinPrice: 0,
        // cartMinPrice:999,
        delBtnWidth: 50,
        radioItems: [{ value: '不杀' }, { value: '杀好(要内脏)' }, { value: '杀好(不要内脏)' }],
        radioSelect: '',
        optionsHidden: true,
        dialogContent: '',
        dialogTitle: '',
        cartShare: 0,
        shareCartShow: 0,
        xcShow:false,
        xcData:[]

    },
    getCartGoods: function (t) {
        var o = wx.getStorageSync("token");
        var that = a
        var th = this

        wx.request({
            url: a.apiUrl("cart"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": o
            },
            success: function (a) {

                var o, e = "";
                for (var n in a.data.cart_list) {
                    o = a.data.data.cart_list[n].goods_attr.split("\n"), e = "";
                    for (var i in o) "" != o[i] && (e += o[i] + ",");
                    a.data.cart_list[n].goods_attr = e.substring(0, e.length - 1);
                }
                var shareCartShow = a.data.data.shareCartShow;
                "" == a.data.data.cart_list || void 0 == a.data.data.cart_list ? t.setData({
                    shopLists: "",
                    indexGoods: a.data.data.best_goods,
                    xcData: a.data.data.xcData,
                    xcShow: a.data.data.xcData != undefined,
                    //shareCartShow:a.data.data.shareCartShow,
                    cartData: a.data.data,
                    cartMinPrice: a.data.data.cartMinPrice
                }) : t.setData({
                    shopLists: a.data.data.cart_list,
                    xcData: a.data.data.xcData,
                    xcShow: a.data.data.xcData != undefined,
                    total: a.data.data.total,
                    indexGoods: a.data.data.best_goods,
                    //shareCartShow:a.data.data.shareCartShow,
                    cartData: a.data.data,
                    cartMinPrice: a.data.data.cartMinPrice
                });

                wx.getSystemInfo({
                    success: (result) => {
                        if (result.platform == "ios") {
                            t.setData({
                                shareCartShow: shareCartShow && 0
                            })
                        } else {
                            t.setData({
                                shareCartShow: shareCartShow && 1
                            })
                        }
                    },
                    fail: () => { },
                    complete: () => { }
                });

                that.setCartNum()
                console.log(a.data.data.noStockGoods);
                //库存不足商品
                if (a.data.data.noStockGoods != undefined) {
                    var dialogContent = []
                    var noStockRec = [];
                    for (var gg in a.data.data.noStockGoods) {
                        dialogContent[gg] = a.data.data.noStockGoods[gg].goods_name + '\n';
                        noStockRec[gg] = a.data.data.noStockGoods[gg].rec_id;
                    }
                    th.setData({
                        dialogContent: dialogContent,
                        dialogTitle: '以下商品库存不足',
                        noStockRec: noStockRec
                    });
                    th.showNoStockDialog();
                    return;
                } else {
                    th.noStockdialog.hideDialog();
                }
                //改价商品
                if (a.data.data.diff_goods != undefined) {
                    var dialogContent = []
                    for (var gg in a.data.data.diff_goods) {
                        dialogContent[gg] = /* (parseInt(gg)+1)+'、'+ */a.data.data.diff_goods[gg].goods_name + '单价从' + a.data.data.diff_goods[gg].goods_price + '=>' + a.data.data.diff_goods[gg].shop_price + '\n';
                    }
                    th.setData({
                        dialogContent: dialogContent,
                        dialogTitle: '价格变更提醒'
                    });
                    th.showDialog();
                }
                th.asyncCartGoods();
            }
        });
    },
    onLoad: function (options) {
        t = wx.getStorageSync("token");
        var a = this;
        //this.getCartGoods(a);
    },
    onShow: function () {
        var t = this;
        t.setData({
            is_first_action: !0,
            dialogContent: '',
            dialogTitle: '',
            noStockRec: []
        });
        t.noStockdialog != undefined && t.noStockdialog.hideDialog();
        t.dialog != undefined && t.dialog.hideDialog();

        this.getCartGoods(t), t.setData({
            is_first_action: !0
        });

        /* wx.request({
            url: getApp().apiUrl("index/getCartMinPrice"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
            },
            success: function (a) {
                wx.setStorageSync('cartMinPirce', a.data.data)
                t.setData({
                    cartMinPrice: a.data.data,
                })
            }
        }); */
    },
    onReady: function () {
        var that = this;
        //获得dialog组件
        that.dialog = that.selectComponent("#dialog");
        that.noStockdialog = that.selectComponent("#noStockdialog");
        //         console.log(that.dialog);
    },
    asyncCartGoods: function () {
        var token = wx.getStorageSync("token");
        let goods = this.data.indexGoods;
        var that = this;

        wx.request({
            url: getApp().apiUrl("index/getCartGoods"),
            method: "post",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            success: function (t) {
                if (t.data.data.length == undefined) {
                    t.data.data = [];
                }
                let cartGoods = t.data.data;
                goods.forEach((item, key) => {
                    goods[key].cart_num = 0;
                    cartGoods.forEach((val) => {
                        if (val.goods_id == item.goods_id) {
                            /*var cartNum = 'goods[' + key + '].cart_num';
                            that.setData({
                                [cartNum]: val.goods_number
                            });*/
                            goods[key].cart_num = val.goods_number
                            goods[key].cart_id = val.rec_id
                        }

                    })

                })

                that.setData({
                    indexGoods: goods
                });

            }
        });

    },
    radioChange: function (e) {
        var items = this.data.radioItems;
        for (var i = 0; i < items.length; ++i) {
            items[i].checked = items[i].value == e.detail.value
            items[i].checked && this.setData({
                radioSelect: items[i].value
            });
        }

        this.setData({
            radioItems: items
        });
    },
    closeFloat: function () {
        this.setData({
            optionsHidden: true
        })
    },
    goodsCheckout: function (t) {
        let type = t.currentTarget.dataset.type;
        let index = t.currentTarget.dataset.index;
        let opt = t.currentTarget.dataset.opt;
        let goods = this.data.indexGoods;
        let that = this;
        if (type == 'jia') {
            if (goods[index].is_fish == 1 && opt != 1) {
                goods[index].index = index;
                that.setData({
                    optionsHidden: false,
                    fishGoods: goods[index]
                })
                return false;
            }

            if (opt == 1 && that.data.radioSelect == '') {
                wx.showToast({
                    title: "请选择处理方式",
                    image: "../../images/failure.png",
                    duration: 2e3
                })
                return false;
            }
            if (opt == 1 && that.data.radioSelect != '') {
                t.remarks = that.data.radioSelect;
            }
            getApp().goodsCheckout_v2(t, false).then((res) => {
                if (res.data.data.code == -1) {
                    wx.showModal({
                        title: '提示',
                        content: res.data.data.msg,
                        showCancel: false,
                    })
                } else {
                    that.setData({
                        optionsHidden: true,
                    })
                    that.onShow()
                }
            })


        } else {
            goods[index].cart_num--;
            if (goods[index].cart_num > 0) {
                getApp().goodsCartUpdate(t, goods[index].cart_num, false)
            } else {
                getApp().goodsCartDelete(t, false)

            }
            that.onShow()
        }


    },
    textCount: function (o) {
        var e, n, i = this, s = o.currentTarget.dataset, r = i.data.total, d = i.data.shopLists, c = [];
        var l = o.detail.value
        for (var u in d) c.push(d[u]);
        for (n in c) if (void 0 != (e = c[n].find(function (t) {
            return t.rec_id == s.id;
        }))) break;
        if (parseInt(l) < 1) {
            wx.showModal({
                title: "提示",
                content: "商品数量不能小于1",
                success: function (o) {
                    l = '1'
                    console.log(l)
                    e.goods_number = parseInt(l), r.count = parseInt(l), d.total_price += parseInt(e.goods_price)
                    wx.request({
                        url: a.apiUrl("cart/update"),
                        data: {
                            id: s.id,
                            goods_id: s.cid,
                            amount: e.goods_number
                        },
                        header: {
                            "Content-Type": "application/json",
                            "X-ECTouch-Authorization": t
                        },
                        method: "POST",
                        success: function (res) {
                            console.log(res);
                            if (res.data == 1) {
                                i.onShow();

                            } else {
                                wx.showModal({
                                    title: '提示',
                                    content: res.data.data.msg,
                                    showCancel: false,
                                    success: function () {
                                        i.onShow();
                                    }
                                })
                            }

                        }
                    });
                }
            });
        } else {
            e.goods_number = parseInt(l), r.count = parseInt(l), d.total_price += parseInt(e.goods_price)
            wx.request({
                url: a.apiUrl("cart/update"),
                data: {
                    id: s.id,
                    goods_id: s.cid,
                    amount: e.goods_number
                },
                header: {
                    "Content-Type": "application/json",
                    "X-ECTouch-Authorization": t
                },
                method: "POST",
                success: function (res) {
                    console.log(res);
                    if (res.data == 1) {
                        i.onShow();

                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.data.data.msg,
                            showCancel: false,
                            success: function () {
                                i.onShow();
                            }
                        })
                    }

                }
            });
        }
        console.log(l)
    },
    addCount: function (o) {
        var e, n, i = this, s = o.currentTarget.dataset, r = i.data.total, d = i.data.shopLists, c = [];
        console.log(s, d);
        for (var u in d) {
            c.push(d[u]);
        }
        for (n in c) if (void 0 != (e = c[n].find(function (t) {
            return t.rec_id == s.id;
        }))) break; console.log(e);

        wx.request({
            url: a.apiUrl("cart/update"),
            data: {
                id: s.id,
                goods_id: s.cid,
                amount: e.goods_number + 1
            },
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": t
            },
            method: "POST",
            success: function (res) {
                console.log(res);
                if (res.data.data == 1) {
                    i.onShow();
                } else {
                    wx.showModal({
                        title: '提示',
                        content: res.data.data.msg,
                        showCancel: false,
                    })
                }

            }
        });
    },
    minusCount: function (o) {
        var e, n, i = this, s = o.currentTarget.dataset, r = (this.data.total, this.data.shopLists), d = [];
        for (var c in r) d.push(r[c]);
        for (n in d) if (void 0 != (e = d[n].find(function (t) {
            return t.rec_id == s.id;
        }))) break;
        if (r.total_price -= parseInt(e.goods_price), parseInt(r.total_price) < 0) r.total_price += parseInt(r.goods_price); else {
            if (e.goods_number == 1) {
                return false;
            }
            wx.request({
                url: a.apiUrl("cart/update"),
                data: {
                    id: s.id,
                    goods_id: s.cid,
                    amount: e.goods_number - 1
                },
                header: {
                    "Content-Type": "application/json",
                    "X-ECTouch-Authorization": t
                },
                method: "POST",
                success: function (res) {
                    if (res.data.data == 1) {
                        i.onShow();
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.data.data.msg,
                            showCancel: false,
                        })
                    }

                }
            });
        }
    },
    del: function (o) {
        var e = this, n = o.currentTarget.dataset;
        wx.showModal({
            title: "提示",
            content: n.id > 0 ? "您确定要移除当前商品吗?" : "您确定清空购物车吗？",
            success: function (o) {
                o.confirm && wx.request({
                    url: a.apiUrl("cart/delete"),
                    data: {
                        id: n.id
                    },
                    method: "POST",
                    header: {
                        "Content-Type": "application/json",
                        "X-ECTouch-Authorization": t
                    },
                    success: function (t) {
                        e.onShow();
                    }
                });
            }
        });
    },
    flowcartBtn: function () {
        wx.switchTab({
            url: "../index/index"
        });
    },


    showDialog() {
        this.dialog.showDialog();
    },

    showNoStockDialog() {
        this.noStockdialog.showDialog();
    },

    //取消事件
    _cancelEvent() {
        console.log('你点击了取消');
        this.dialog.hideDialog();
    },
    //确认事件
    _confirmEvent() {
        console.log('你点击了确定');
        this.dialog.hideDialog();
    },

    //取消事件
    _cancelNoStockEvent() {
        this.noStockdialog.hideDialog();
    },
    //确认事件
    _confirmNoStockEvent() {
        console.log(this.data.noStockRec);
        var that = this;
        var token = wx.getStorageSync("token");
        wx.request({
            url: a.apiUrl("cart/delete"),
            data: {
                rec_id: that.data.noStockRec,
                type: 'multi'
            },
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            method: "POST",
            success: function (res) {
                that.noStockdialog.hideDialog();
                that.onShow();
            }
        });

    },
    chooseXiaocong: function (e) {
        console.log(e);
    },
    goodsAddToCart: function (e) {
        var that = this;
        a.goodsCheckout_v2(e).then((res) => {
            if (res.data.data.code == -1) {
                wx.showModal({
                    title: '提示',
                    content: res.data.data.msg,
                    showCancel: false,
                })
            } else {
                that.onShow();
            }
        });
    },
    flowCheckoutBtn: function (t) {
        var o = this, e = wx.getStorageSync("token");
        wx.request({
            url: a.apiUrl("flowCheck"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": e
            },
            success: function (res) {
                if (res.data.data.code == 1) {
                    wx.setStorageSync("flowcheckout", {
                        from: "checkout"
                    }), 1 == o.data.is_first_action && (o.setData({
                        is_first_action: !1
                    }), wx.request({
                        url: a.apiUrl("user/address/list"),
                        method: "POST",
                        header: {
                            "Content-Type": "application/json",
                            "X-ECTouch-Authorization": e
                        },
                        success: function (t) {
                            "" != t.data.data ? wx.navigateTo({
                                url: "../flow/checkout"
                            }) : wx.navigateTo({
                                url: "../address/create"
                            });
                        }
                    }));


                } else {
                    wx.showModal({
                        title: '提示',
                        content: res.data.data.msg,
                        showCancel: false,

                    })
                }
            }
        });
    },

    /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle: function (start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    onShareAppMessage: function (res) {
        //if (res.from === 'button') {
        var e = wx.getStorageSync("token");
        wx.request({
            url: a.apiUrl("index/cartShare"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": e
            },
            success: function (res) {

            }
        });
        //}
        return {
            title: "什么？免费领鸡蛋？速戳查看~",
            imageUrl: 'https://piwx.llmaicai.com/images/sharecart.png',
            path: '/pages/flow/index?shareCart=1'
        };
    },
    onShareTimeline: function (res) {
        var e = wx.getStorageSync("token");
        wx.request({
            url: a.apiUrl("index/cartShare"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": e
            },
            success: function (res) {

            }
        });
        return {
            title: "什么？免费领鸡蛋？速戳查看~",
            query: 'shareCart=1',
            imageUrl: 'https://piwx.llmaicai.com/images/sharecart.png'
        };
    },
    checkAll: function (res) {
        var that = this;
        var checkall = that.data.cartData.checkAll;


        that.checkCart(null, checkall ? 0 : 1);
        return;

        that.setData({
            "cartData.checkAll": !checkall
        });
        //if(that.data.cartData.checkAll == true){
        for (var i in that.data.shopLists[0]) {
            console.log(i, that.data.shopLists[0][i]);
            var key = "shopLists[0][" + i + "].is_invalid";
            that.setData({
                [key]: !checkall
            });
        }
        //}
    },
    checkMe: function (e) {
        var that = this;
        console.log(e.currentTarget.dataset.id);
        var is_invalid = that.data.shopLists[0][e.currentTarget.dataset.index].is_invalid;
        console.log(e.currentTarget.dataset.index, that.data.shopLists[0]);
        that.checkCart(e.currentTarget.dataset.id, is_invalid ? 0 : 1);
    },
    checkCart: function (rec_id, is_invalid) {
        var that = this;
        var token = wx.getStorageSync("token");
        wx.request({
            url: a.apiUrl("cart/checkCart"),
            method: "POST",
            data: {
                rec_id: rec_id,
                is_invalid: is_invalid
            },
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            success: function (res) {
                console.log(res);
                if (res.data.code == 200) {
                    that.onShow();
                } else {
                    wx.showToast({
                        title: res.data.data,
                        icon: 'none',
                        image: '',
                        duration: 1500,
                        mask: true,
                        success: (result) => {

                        },
                        fail: () => { },
                        complete: () => { }
                    });

                }
            }
        });
    }
});
